<?php

namespace App\Api\Models;

use DateTimeInterface;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class ModuleModel extends Model
{
    use HasFactory;

    protected $table = 'module';
    protected $dateFormat = 'U';//这个时间字段被为被格式化为UNIX 时间戳的形式存储

    //toArray 时间转换问题
    protected function serializeDate(DateTimeInterface $date)
    {
        return $date->format('Y-m-d H:i:s');
    }

    public function secondModule()
    {
        return SELF::hasMany(SELF::class, 'upper_module_id', 'id');
    }

    //子账号可用权限信息
    static public function usefulPermission($firstModule, $secondModule)
    {
        return SELF::select(
            'id',
            'module_name',
            'module_img',
            'sort',
            'type',
        )
            ->with('secondModule', function($query) use ($secondModule) {
                $query->select(
                    'id',
                    'module_name',
                    'module_img',
                    'upper_module_id',
                    'sort',
                    'type',
                )
                    ->where('delete_flag', 0)
                    ->whereIn('id', $secondModule)
                    ->orderBy('sort', 'asc')
                    ->orderBy('id', 'desc');
            })
            ->where('delete_flag', 0)
            ->whereIn('id', $firstModule)
            ->orderBy('sort', 'asc')
            ->orderBy('id', 'desc')
            ->get()->toArray();
    }
}
